package com.me.dao.imp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import com.me.dao.UserDao;
import com.me.entity.User;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

public class UserDaoImp implements UserDao {

    private JdbcTemplate jdbcTemplate;

    @Override
    public User findUserByName(String username) {
        String sqlStr = "select userId,username,credits,lastVisit from user where username=?";
        final User user = new User();
        jdbcTemplate.query(sqlStr, new Object[]{username},
                new RowCallbackHandler() {

                    @Override
                    public void processRow(ResultSet rs) throws SQLException {
                        user.setUserId(rs.getInt("userId"));
                        user.setUsername(rs.getString("username"));
                        user.setCredits(rs.getInt("credits"));
                        user.setLastVisit(rs.getDate("lastVisit"));
                    }
                });
        return user;
    }

    @Override
    public int getMatchCount(String username, String password) {
        String sqlStr = "select count(*) from user where username=? and password=?";
        return jdbcTemplate.queryForInt(sqlStr, new Object[]{username, password});
    }

    @Override
    public void updateLoginInfo(User user) {
        String sqlStr = "update user set credits=?,lastIP=?,lastVisit=? where userId=?";
        jdbcTemplate.update(sqlStr, new Object[]{user.getCredits(), user.getLastIP(), user.getLastVisit(), user.getUserId()});
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void addUser(User user) {
        String sqlStr = "insert into user(username,password,credits,lastVisit,lastIP) values(?,?,?,?,?)";
        //System.out.print(user.getUsername()+","+user.getPassword()+","+user.getCredits()+","+user.getLastVisit()+","+user.getLastIP());
        jdbcTemplate.update(sqlStr, new Object[]{user.getUsername(), user.getPassword(), user.getCredits(), user.getLastVisit(), user.getLastIP()});
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
}
